import React, { useState, useEffect } from 'react'
import { Space, Divider, List, message } from 'antd'
import style from './Index.module.less'
import { PlusOutlined } from '@ant-design/icons'
import { getConfigListRequest, delConfigRequest } from './ajax'
import { awaitWrap, confirmAction } from '@src/assets/js/tool'
import ConfigModal from '../ConfigModal/Index'
// import classNames from 'classnames'

async function initData (currentType, setData, setLoading) {
  setLoading(true)
  const [e, d] = await awaitWrap(getConfigListRequest(currentType.type))
  setLoading(false)
  if (e !== null) {
    return message.warning(e.message)
  }
  setData(d)
}

async function delHandle (data, refreshFn) {
  const hide = message.loading('删除中', 60)
  const [e] = await awaitWrap(delConfigRequest(data))
  hide()
  if (e) {
    return message.warning(e.message)
  }
  message.success('删除成功')
  refreshFn()
}

function Main ({ currentType }) {
  const [data, setData] = useState([])
  const [loading, setLoading] = useState(false)
  const [modifyData, setModifyData] = useState(null)
  const [visible, setVisible] = useState(false)
  const refreshFn = () => {
    initData(currentType, setData, setLoading)
  }
  useEffect(() => {
    if (currentType) {
      initData(currentType, setData, setLoading)
    }
  }, [currentType])
  return (
    <div className={style.container}>
      <div className={style.title}>
        <span>{currentType && currentType.type}</span>
      </div>
      <ul>
        <ConfigModal currentType={currentType} visible={visible} data={modifyData} hide={() => { setVisible(false); setModifyData(null) }} refreshFn={refreshFn} />
        <List
          dataSource={data}
          loading={loading}
          renderItem={(item, i) => {
            return (
              <li key={i} className={style['config-li']}>
                <span className={style['config-li-text']}>{item.title}</span>
                <Space split={<Divider type='vertical' />}>
                  <a onClick={() => { setModifyData(item); setVisible(true) }}>修改</a>
                  <a className={style.del} onClick={() => confirmAction(`您确定要删除"${item.title}"吗？`, () => delHandle(item, refreshFn))}>删除</a>
                </Space>
              </li>
            )
          }}
        />
      </ul>
      {currentType && (
        <button className={style['add-btn']} onClick={() => { setVisible(true); setModifyData(null) }}>
          <PlusOutlined />
          <span>添加配置项</span>
        </button>
      )}
    </div>
  )
}

export default Main
